package cn.itcast.tanhua.server.service;

import cn.itcast.tanhua.common.pojo.User;
import cn.itcast.tanhua.common.pojo.UserInfo;
import cn.itcast.tanhua.common.utils.UserThreadLocal;
import cn.itcast.tanhua.dubbo.server.pojo.RecommendUser;
import cn.itcast.tanhua.dubbo.server.vo.PageInfo;
import cn.itcast.tanhua.server.vo.PageResult;
import cn.itcast.tanhua.server.vo.RecommendUserQueryParam;
import cn.itcast.tanhua.server.vo.TodayBest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName TodayBestService
 * @Description 今日佳人业务类，需要调用其他业务类实现3大功能：校验token、查询缘分值用户、在数据库查询该用户的基本信息
 * @Author WU
 * @Date 2021/5/28 15:51
 * @Version 1.0
 */
@Service
public class TodayBestService {
    //    注入查询缘分值最高用户的业务类对象
    @Autowired
    private RecommendUserService recommendUserService;

    //    注入校验token的业务类对象
    @Autowired
    private UserService userService;

    //    注入查询用户基本信息的业务类对象
    @Autowired
    private UserInfoService userInfoService;

    //    注入默认最佳推荐
    @Value("${tanhua.sso.default.user}")
    private Long defaultUser;


    /**
     * @Description: 今日佳人业务类，需要调用其他业务类实现3大功能：校验token、查询缘分值用户、在数据库查询该用户的基本信息
     * @Param: token
     * @return:
     * @Author: Mr.Tan
     * @Date: 2021/5/28
     */
    public TodayBest queryTodayBest() {
//        通过sso的接口校验token
        User user = UserThreadLocal.get();

//        校验token通过后查询今日佳人
        TodayBest todayBest = this.recommendUserService.queryTodayBest(user.getId());
//        如果没有查询到则给出默认推荐
        if (null == todayBest) {
            todayBest = new TodayBest();
            todayBest.setId(defaultUser);
            todayBest.setFateValue(80);
        }

//        通过用户id，查询数据库，填充今日佳人的基本信息
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(todayBest.getId());
//        如果查询到的基本信息为空，则返回空
        if (null == userInfo) {
            return null;
        }

//        查询到的基本信息不为空，则填充信息并返回
        todayBest.setAge(userInfo.getAge());
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ","));

        return todayBest;
    }


    /**
     * @Description: 用户推荐列表查询
     * @Param: token/param
     * @return:
     * @Author: Mr.Tan
     * @Date: 2021/5/28
     */
    public PageResult queryRecommendation( RecommendUserQueryParam param) {
//        通过拦截器校验token
        User user = UserThreadLocal.get();

        //        校验token通过后查询推荐列表
//        添加分页参数
        PageResult pageResult = new PageResult();
        pageResult.setPage(param.getPage());
        pageResult.setPagesize(param.getPagesize());
//          分页查询
        PageInfo<RecommendUser> pageInfo = this.recommendUserService.queryRecommendUserList(user.getId(), param.getPage(), param.getPagesize());
//        获取到推荐用户的数据
        List<RecommendUser> records = pageInfo.getRecords();
//        如果没查到数据则
        if (CollectionUtils.isEmpty(records)) {
            return pageResult;
        }
//        将缘分值放到一个集合中
        Map<Long,Integer> fateMap = records.stream().collect(Collectors.toMap(record -> record.getUserId(),
                record -> {
                    double score = Math.floor(record.getScore());
                    return Double.valueOf(score).intValue();
                }
             ));
//        不为空则需要填充信息
//        手机用户id，用set集合去重
        Set<Long> userIds = new HashSet<>();
        for (RecommendUser record : records) {
            userIds.add(record.getUserId());

        }
//          查询基本信息
//        构建查询条件，用于查询数据库
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();

        //用户id参数
        queryWrapper.in("user_id", userIds);

        if (StringUtils.isNotEmpty(param.getGender())) {
            //需要性别参数查询
//            queryWrapper.eq("sex", StringUtils.equals(param.getGender(), "man") ? 1 : 2);
        }

        if (StringUtils.isNotEmpty(param.getCity())) {
            //需要城市参数查询
//            queryWrapper.like("city", param.getCity());
        }

        if (param.getAge() != null) {
            //设置年龄参数，条件：小于等于
//            queryWrapper.le("age", param.getAge());
        }

        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);
//        没有查到信息
        if (CollectionUtils.isEmpty(userInfoList)) {
            return pageResult;
        }

//        查到则填充基本信息和缘分值
        List<TodayBest> todayBests = new ArrayList<>();
        TodayBest todayBest;
        for (UserInfo userInfo : userInfoList) {
            todayBest = new TodayBest();

            todayBest.setId(userInfo.getUserId());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
            todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
            todayBest.setAge(userInfo.getAge());
//            添加缘分值
            todayBest.setFateValue(fateMap.get(userInfo.getUserId()));

            todayBests.add(todayBest);

        }

        //按照缘分值进行倒序排序
        Collections.sort(todayBests, (o1, o2) -> new Long(o2.getFateValue() - o1.getFateValue()).intValue());
        pageResult.setItems(todayBests);
        return pageResult;
    }
}
